﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 所有非叶节点的父抽象类
    /// 默认的Tick方法不会返回Failure，仅在所有子节点都被执行完后返回Success
    /// 向上传递Abort信息，子结点执行中或尚未遍历完子节点都返回Continue
    /// </summary>
    public abstract class Branch : BTNode
    {
        protected int activeChild;
        protected bool needToReset = false;
        protected List<BTNode> children = new List<BTNode>();
        public virtual Branch OpenBranch(params BTNode[] children)
        {
            for (var i = 0;i < children.Length;i++)
            {
                this.children.Add(children[i]);
            }
            return this;
        }
        protected virtual void ResetSelf()
        {
            activeChild = 0;
        }
        protected virtual void ResetChildren()
        {
            for (var i = 0;i < children.Count;i++)
            {
                //这里要加判断，未必每个child都是branch
                if(children[i] is Branch)
                {
                    Branch b = children[i] as Branch;
                    b.needToReset = true;
                }
            }
        }
        public override BTState Tick(int BTid)
        {
            switch (children[activeChild].Tick(BTid))
            {
                case BTState.Continue:
                    return BTState.Continue;
                case BTState.Abort:
                    return BTState.Abort;
                default:
                    activeChild++;
                    if (activeChild == children.Count)
                    {
                        //这里无法通过needToReset设置标记位来做，否则会影响到子类的特性标记
                        //TODO考虑是否可以优化
                        //ResetSelf();
                        //ResetChildren();
                        return BTState.Success;
                    }
                    return BTState.Continue;
            }
        }
    }
}
